package middleware

import (
	"strconv"

	"rbac-abac-demo/utils"

	"github.com/gin-gonic/gin"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		userIDStr := c.Query("user_id")
		if userIDStr == "" {
			c.JSON(400, gin.H{"error": "请提供 user_id 查询参数"})
			c.Abort()
			return
		}

		id, err := strconv.Atoi(userIDStr)
		if err != nil {
			c.JSON(400, gin.H{"error": "user_id 必须是数字"})
			c.Abort()
			return
		}

		for _, u := range utils.Users {
			if u.ID == id {
				c.Set("user", &u)
				c.Next()
				return
			}
		}

		c.JSON(401, gin.H{"error": "用户不存在"})
		c.Abort()
	}
}
